using Microsoft.Xna.Framework;

namespace Life
{
    // Container that evenly spaces children horizontally or vertically
    // TODO: Auto sizing children will result in unnecessary invalidation of parents, because:
    // TODO: Layout* calls children's Layout, and InvalidateAutoSize calls parent's InvalidateAutoSize
    // TODO: So, each child will turn around and tell it's parent to invalidate
    public class PanelControl : Control
    {
        // true => space vertically, false => space horizontally
        private bool _isColumn;
        private float _spacing;

        public PanelControl(bool isColumn, float spacing)
        {
            _isColumn = isColumn;
            _spacing = spacing;
        }

        public void Layout(float xMargin, float yMargin)
        {
            if (_isColumn)
            {
                LayoutColumn(xMargin, yMargin);
            }
            else
            {
                LayoutRow(xMargin, yMargin);
            }
        }

        // Position child components in a column, with the given spacing between components
        private void LayoutColumn(float xMargin, float yMargin)
        {
            float y = yMargin;

            for (int i = 0; i < ChildCount; i++)
            {
                Control child = this[i];
                child.Position = new Vector2 { X = xMargin, Y = y };

                // If child is a PanelControl, invalidate it's size too
                if (child is PanelControl)
                {
                    (child as PanelControl).Layout(xMargin, yMargin);
                }

                y += child.Size.Y + _spacing;
            }

            InvalidateAutoSize();
        }

        // Position child components in a row, with the given spacing between components
        private void LayoutRow(float xMargin, float yMargin)
        {
            float x = xMargin;

            for (int i = 0; i < ChildCount; i++)
            {
                Control child = this[i];
                child.Position = new Vector2 { X = x, Y = yMargin };

                // If child is a PanelControl, invalidate it's size too
                if (child is PanelControl)
                {
                    (child as PanelControl).Layout(xMargin, yMargin);
                }

                x += child.Size.X + _spacing;
            }

            InvalidateAutoSize();
        }
    }
}
